<?php

namespace server\dao;

use phpDocumentor\Reflection\Types\Object_;
use Yii;
use yii\mongodb\Query;

/**
 * This is the model class for collection "runtime".
 *
 * @property \MongoDB\BSON\ObjectID|string $_id
 * @property mixed $id
 * @property mixed $info
 */
class Log extends \common\core\server\ActiveRecord
{

    public $start;					// 在这张表中的位置
    public $size;					// 这张表的日志长度
    public $streamOffset;			// 这张表的起始位置在整个流中的位置
    /**
     * {@inheritdoc}
     */
    public static function collectionName()
    {
        return 'log';
    }

    /**
     * {@inheritdoc}
     */
    public function attributes()
    {
        return [
            '_id',
            'time',
            'info',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['time', 'info'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            '_id' => 'ID',
            'time' => 'Time',
            'info' => 'Info',
        ];
    }

    public function getLogList($params, $isAll)
    {
        $query = new Query();
        $query->from('log');
        if ($this->issetAndEmpty($params, 'ip')) {
            $query->andWhere(['uuid' => $params['ip']]);
        }
        if ($this->issetAndEmpty($params, 'module')) {
            $query->andWhere(['module' => $params['module']]);
        }
        if ($this->issetAndEmpty($params, 'startTime')) {
            $startTime = date('Y-m-d',$params['startTime']);
            $startTime = strtotime($startTime);
            $query->andWhere(['timestamp'=>['$gte'=>(int)$startTime]]);
        }
        if ($this->issetAndEmpty($params, 'endTime')) {
            $endTime = date('Y-m-d 23:59:59',$params['endTime']);
            $endTime = strtotime($endTime);
            $query->andWhere(['timestamp'=>['$lte'=>(int)$endTime]]);
        }
        $query->orderBy('timestamp desc');
        //return $query->createCommand()->getRawSql();
        return $isAll ? $query->all() : $this->mongodbPage($query);
    }

    public function getLogModule(){
        $q = new Query();
        $pipelines[] = [
            '$group' => [
                '_id' => '$module',
            ],
        ];
        $pipelines[] = ['$sort' => ['timestamp' => -1]];//1正序 -1倒序
        return $res = $q->from('log')->getCollection()->aggregate($pipelines);
    }
}
